
/*
*Pool Public Licence version 0.1 or later
*Released on 20th April 2008.
*Any voilations can be repoted at paritosh@wikiocean.net
*What is treated as voilations can be found at www.wikiocean.net/ppl1-voilations* 
******************************************************************************
* The contents of this file are subject Affero GPL v3 and later with additional conditions.
* The additional conditions are to be considered as part of the Affero GPL v3 and later.
* The additional conditions will supersede the Affero GPLv3 and later in case of conflict.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the License at http://www.gnu.org/licenses/agpl.html
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya.
* created by Paritosh Pungaliya are Copyright (C) Paritosh Pungaliya; All Rights Reserved.
* Contributions are Copyright (C) 2001-2008 Paritosh Pungaliya.

* Objective of the additional terms (license) 
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencie(s).
* 3) To avoid a situation where big corporates or investors can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the openness changes in companies that get Venture Capital funding.)
* (if you agree to this logic I invite you to our group to work together)

* Additional conditions
*  0) Source code will also include
* 	a) data dictionaries, data ontologies which are used to alter the behavior of code or to control           the features of application.
* 	b) Any code generated or derived automatically or manually from this code or logic
*  1) The revenue generated by deploying, implementing , selling services and other activities
*  	 based on this source code should be shared 100%, between the people working on it.
*  2) Capital invested should be given only fixed rate of return or linked to revenue/surplus growth for limited time.
*  3) People working on the project should always have an option to replace the capital provider in full or part with lower cost capital.
*  4) Their should not be any ownership which can be sold as a claim on future profit to be generated from the work of people working on the code.
*  5) Brand thus generated should belong to the group.
*  6) For old and new members revenue sharing should be equal for same work equivalent.
*  7) The share of revenue should be decided by bidding for work before allocation of work within the group.
*  8) Before bidding various method of measuring the work should be clearly defined and published in public domain. Any change in process should also be publised in public domain imediately.
*  9) All data related to to revenue sharing should be published as and when generated in public domain.
*  10) For group of people having size more than 10 people will have to make it open online for others to participate in bids. 
*  11) All people involved in related and sub project will be treated as a group.
*  12) Once this license is being used for a certain code then all and any other software services being provided by the group should complusorilly come under 100% revenue sharing.
*  13) Cross subsidization should not happen under this revenue share, no additional benefit should be drawn from the people, by the employing agency.
*  14) Any position or knowledge or legal structure created relating to people working on code, which adversely affects the spirit of 100% revenue share will be treated as a violation.
*  15) Revenue sharing defined.
*     a) includes direct revenue and also intangible gains like brand, and organization.
*     b) No personal judgment should be involved in judging the distribution of revenue.It has to be pre-defined formula based.
*     c)100% of revenue should be shared before expenses and recievers should have control over what expenses to incur.
*     d)For the work done in any month by contributing group member, working on any project can be given revenue share from the work done by the group, for a maximum of 18 months after that month.
*     e)Revenue should be apportioned to the month in which work is done and not when received.
*  The group fulfilling the above conditions also has to be a wiki ecosystem further defined in www.wekosystem.org or read about Wekosystem at www.wikiocean.net

*  ******************************************************************************
*/  
package smsBean;

import java.sql.ResultSet;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import control.Command;
import dbmanager.DBManager;

//import pool.bean.Transaction_details_Bean;

import timer.ExecutionTimer;
import timer.TimerRecordFile;
import utility.CharAt;
import utility.MessageGenerator;

import utility.Index;



public class SmsTransaction_details extends SubSmsBean
{

	SmsTd_property_details stdpd;
	
	private String masterTable = "transaction";
	private String td_tableName = "transaction_details";
	
	private String msg=" ";
	private String tid="no$";
	private String spChar="";				 
	 
	private Vector<Object> TransDetailVector  = new Vector<Object>();
	 
	private Vector<Object> OldTransDetailVector  = new Vector<Object>();
	private Vector<Object> NewTransDetailVector = new Vector<Object>();
	 
	private Hashtable<Object,Object> ViewHashtable = new Hashtable<Object, Object>();
	
	 //Transaction_details_Bean tdBean;
	 
	 public SmsTransaction_details(){}
	 
	 public SmsTransaction_details(DBManager sqldb)
	 {
		 this.sqlDB = sqldb;
	 }
	 
	public SmsTransaction_details(DBManager sqldb,String msg,String process,String Request)
	{
		ExecutionTimer t = new ExecutionTimer();
		t.start();
		this.request = Request;
		this.process = process;
		this.sqlDB = sqldb;
		message = msg;
		this.msg = msg;		
		t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("SMS.tablename","Transaction_details","Transaction_details",t.duration());
	}
	
	
	/**
	 * In initializeToAdd method of Transaction_details
	 * put the hashMap in TransactionDetailMap hashtable.
	 * @return TransactionDetailMap is a Hashtable which stores object of Transaction_details 
	 * It contains the all the fields of Transaction_details which presents in 
	 * given message e.g. Tid,item,qty,rate,amount. 
	 *
	 */
	public Hashtable<Object,Object> initializeToAdd()
	{
		ExecutionTimer t = new ExecutionTimer();
		t.start();
		 Hashtable<Object,Object> TransactionDetailMap = new Hashtable<Object,Object>();	
		stdpd = new SmsTd_property_details(sqlDB, message, process,request);
        TransactionDetailMap.putAll(initTransaction_details());
        if(TransactionDetailMap.containsKey("ErrorInput"))
		{
			return TransactionDetailMap;
		}
        
         String tidmsg="";
        Command cp = new Command(masterTable, sqlDB);
        Hashtable<Object,Object> tidMap = new Hashtable<Object,Object>();
        
			try 
			{
				tidmsg=message.substring(0,Index.indexOf(message,spChar));
			}
			catch (RuntimeException e) 
			{
				TransactionDetailMap.put("ErrorInput", "insert tid");
				 return TransactionDetailMap;
			}
			tidMap.putAll(cp.getHashCommand(td_tableName, tidmsg, process));
            
            if(tidMap.containsKey("ErrorInput"))
	        {       	
	            return tidMap;
	        }
            tid=tidMap.get("tid").toString();		
            
           insertTid(tid);
		
		t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("SMS.tablename","Transaction_details","initializeToAdd",t.duration());
        return TransactionDetailMap;
	}

	/**
	 * this function inserts tid in each hashtable given in PropertyVector
	 *  @param tid - stores tid as a string value
	 */
	@SuppressWarnings("unchecked")
	private void insertTid(String tid)
	{
		ExecutionTimer t = new ExecutionTimer();
		t.start();
		for(Object object : TransDetailVector)
		{
			Hashtable<Object,Object> hashtable = (Hashtable<Object, Object>)object;
			Enumeration<Object> enumt = hashtable.keys();
			Hashtable<Object,Object> tempHash = (Hashtable<Object, Object>)enumt.nextElement();
			tempHash.put("tid",tid);			
		}
		t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("SMS.tablename","Transaction_details","insertTid",t.duration());
       
	}
	
	/**
	 * In getCount it will count the of the no. of items (transaction details) present
	 * in the given string. It fires the query on transaction_details table and  
	 * gets the specialCharter i.e. ',' from transaction_details and counts the items. 
	 * by taking index of spchar it splits the given string into properties by 
	 * using initTransaction_details method.
	 * @return count no. of  items of transaction_details. 
	 * 
	 */
	public int getCount()
	{
		ExecutionTimer t = new ExecutionTimer();
		t.start();
		int count=0;
		try
		{
			ResultSet rs = sqlDB.getSelect("select fieldname,spchar from command where msgtype = '"+td_tableName+"' and process='"+process+"' and order1>0 order by order1");
			while(rs.next())
			{
				try 
				{
					spChar  = rs.getString("spchar");
					int i = Index.indexOf(message, spChar);
					if(i!=-1)
						break;
				}
				catch (Exception e) {
				}
			}
			msg = message;
			int i = 0;
			while(i<msg.length())
			{	
				char ch = CharAt.CharAT(msg, i);
			    if(ch == spChar.toCharArray()[0])
					count ++;
				i++;
			}				
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("SMS.tablename","Transaction_details","getCount",t.duration());
		return count;
	}
	
	/**
	 * In this method it splits all items and creats an object of each item
	 * which stores in  hashmap.Then add these hashmap in transobject vector. 
	 *
	 */	
	 public Hashtable<Object,Object> initTransaction_details()
	 {
		 ExecutionTimer t = new ExecutionTimer();
			t.start();
		   
		    int index = 0;
		    ResultSet rs;
		    String spchar="";
		    String tdpl_tableName = "td_property_details";
		    
		    Hashtable<Object,Object> TransactionDetailMap = new Hashtable<Object,Object>();	
	        Command cp = new Command(masterTable, sqlDB);
	        int count = cp.getCountof(message, td_tableName, process);
	        if(count != 0)
	        {
	            spChar = cp.getSPchar();
	            index = Index.indexOf(message, spChar, index + 1);
	        }
	   
	        if(count == 0)
	        {
	            TransactionDetailMap.put("ErrorInput", " Transaction must have atleast one transaction_details (Item)");
	            return TransactionDetailMap;
	        }
	        String msg = "";
	        String msg1 = "";
	        while(count != 0) 
	        {
	            if(index == -1)
	                break;
	            count--;
	            try
	            {
	                int start = 0;
	                int end = 0;
	                start = index;
	                msg = message.substring(start + 1);
	                if(msg.contains(spChar))
	                {
	                    end = Index.indexOf(msg, spChar) + start;
	                    msg = message.substring(start, end + 1);
	                }
	                else
	                {
	                    msg = message.substring(start);
	                 }
	                index = end + 1;
	            }
	            catch(Exception e)
	            {
	                e.printStackTrace();
	            }
	           //***************changes  to split Transaction_details from td_property_details************//  
	            msg1=msg;
	            int index1;
	            try
				{
					rs = sqlDB.getSelect("select fieldname,spchar from command where msgtype = '"+tdpl_tableName+"' and process = '"+process+"' and order1>0 and spchar is not null order by  order1 ");
					rs.next();
					spchar = rs.getString("spchar");
					if(msg.contains(spchar))
					{
						index1 = Index.indexOf(msg, spchar);
						msg = msg.substring(0,index1);
					}
					else
					{
						msg1="";
					}
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
	            SmsTransaction_details transobject = new SmsTransaction_details(sqlDB);
	            TransactionDetailMap.putAll(cp.getHashCommand(td_tableName, msg, process));
	            
	            Hashtable<Object, Object> TempMap = new Hashtable<Object, Object>();
	            
	            if(TransactionDetailMap.containsKey("ErrorInput"))
		        {
		        	TempMap .put("ErrorInput",TransactionDetailMap.get("ErrorInput"));
		            return TempMap;
		        }
	            
	            	TempMap.clear();
	      	       //  TempMap.putAll(validate());
	      	        if(TempMap.containsKey("ErrorInput"))
	      	        	return TempMap;
	      	        else
	      	        	TransactionDetailMap.putAll(TempMap);
	          	       
	            transobject.stdpd = new SmsTd_property_details(sqlDB, msg1, process,tdpl_tableName);
	            TempMap.clear();
	            TempMap = transobject.stdpd.initTransactiondetailsPropertyDetails();
	            if(TempMap.containsKey("ErrorInput"))
		        {
		        	return TempMap;
		        }
	            if(TransactionDetailMap.containsKey("ErrorInput"))
		        {
		        	return TempMap;
		        }
	           
	            TempMap = new Hashtable<Object, Object>();
	            
	            TempMap.putAll(TransactionDetailMap);
	            
	            Hashtable<Object, Object> TransactionMap = new Hashtable<Object, Object>();
	            Vector<Object> TdPropertyVector = new Vector<Object>();
	          
	            TdPropertyVector.addAll(transobject.stdpd.getPropertyVector());	            
	         
	            TransactionMap.put(TempMap,TdPropertyVector);
	            
	            TransDetailVector.add(TransactionMap);                           
	        }
	     
	        t.end();
			@SuppressWarnings("unused")
			TimerRecordFile timerFile=new TimerRecordFile("SMS.tablename","Transaction_details","initTransaction_details",t.duration());
	        return TransactionDetailMap;
	 }
	 
	
	
	 /**
	 * initializeToUpdate() creates two vectors(old & new) of hashtables of different properties to be updated
	 */
	public StringBuffer initializeToUpdate()
	{
		ExecutionTimer t = new ExecutionTimer();
		t.start();
        ResultSet rs = null;
        String propertyChar = null;
        Command cp = new Command(request, sqlDB);      
      
        String msg = null;
        
         try
        {
            rs = sqlDB.getSelect((new StringBuilder("select spchar from command where msgtype = '")).append(request).append("' and process = 'add' order by order1").toString());
            rs.next();
      
			String spcharAdd = rs.getString("spchar");
            rs.close();
         }
        catch(Exception e)
        {
            System.out.println("SMS::MasterClass::initializeToUpdate():: Exception while fatching special characters ");
            e.printStackTrace();
        }
        try
        {
            rs = sqlDB.getSelect((new StringBuilder("select fieldname,spchar,order1 from command where msgtype='")).append(request).append("' and from_master='yes' and process='add' and order1>0 order by order1").toString());
            rs.next();
            propertyChar = rs.getString("spchar");
            rs.close();
        }
        catch(Exception e)
        {
            System.out.println("Pipe Char is not Found in Database");  //
        }
        int index = 0;
        
        int count = cp.getCountof(message, td_tableName, process);
        if(count != 0)
        {
            spChar = cp.getSPchar();
            index = Index.indexOf(message, spChar, index + 1);
        }
         tid = message.substring(0 ,index);
         
    	Hashtable<Object,Object> TempHash = new Hashtable<Object,Object>();
        TempHash = cp.getHashCommand(td_tableName,tid, "add");
		if(TempHash.containsKey("ErrorInput"))
	 	{
			return new StringBuffer(TempHash.toString());
		}
		tid = TempHash.get("tid").toString();        
        
        while(count != 0) 
        {
        	  Hashtable<Object,Object> newTransactionMap = new Hashtable<Object,Object>();
              Hashtable<Object,Object> oldTransactionMap = new Hashtable<Object,Object>();
            if(index == -1)
                break;
            count--;
            try
            {
                int start = 0;
                int end = 0;
                start = index;
                msg = message.substring(start+1);
                if(msg.contains(spChar))
                {
                    end = Index.indexOf(msg, spChar) + start;
                    msg = message.substring(start, end + 1);
                } 
                else
                {              	
                	msg = message.substring(start);                
                }
                index = end + 1;
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
            String msg1 = "";
            String msg2 = "";
            int start = 0;
            if(msg.contains(propertyChar))
            {
	            int end1 = 0;
	            end1 = Index.indexOf(msg, propertyChar, end1 + 1);
	            msg1 = msg.substring(start, end1);
	            newTransactionMap.putAll(cp.getHashCommand(td_tableName, msg1, process));
	            if(newTransactionMap.containsKey("ErrorInput"))
			 	{
					return new StringBuffer(newTransactionMap.toString());
				}
	            
	            start = Index.indexOf(msg, propertyChar, start + 1);
	            msg2 = msg.substring(start, msg.length());
	            oldTransactionMap.putAll(cp.getHashCommand(td_tableName, msg2, "add"));
	            if(oldTransactionMap.containsKey("ErrorInput"))
			 	{
					return new StringBuffer(oldTransactionMap.toString());
				}
	            oldTransactionMap.put("tid", tid);
	            
	        	Hashtable<Object, Object> temp = new Hashtable<Object, Object>();
	            temp.putAll(oldTransactionMap);  
	            OldTransDetailVector.add(temp);
            }
            else
            {
            	msg1=msg;
            	newTransactionMap.putAll(cp.getHashCommand(td_tableName, msg1, process));
            	if(newTransactionMap.containsKey("ErrorInput"))
			 	{
					return new StringBuffer(newTransactionMap.toString());
				}
            }      
            
            newTransactionMap.put("tid", tid);
		  
		  	Hashtable<Object, Object> temp1 = new Hashtable<Object, Object>();
		  	temp1.putAll(newTransactionMap);
            NewTransDetailVector.add(temp1);
            
        }      
        t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("SMS.tablename","Transaction_details","initializeToUpdate",t.duration());
        return sbrDTB;
	}
	
	
	/**
	 * initializeToView() creates hashtables of transaction_details object to be viewed 
	 * @return stringbuffer containing details of transaction_details to be viewed  
	 */
	public StringBuffer initializeToView() 
	{		
		
		ExecutionTimer t = new ExecutionTimer();
		t.start();
		
		StringBuffer sbrProperty=new StringBuffer();
		Hashtable<Object,Object> TransactionDetailMap = new Hashtable<Object,Object>();	
		
		//TransactionDetailMap stores all the input information given in the  request 
		//e.g tid(transaction id),item,qty,rate,amount 
		
		Command cp = new Command(td_tableName, sqlDB);
		TransactionDetailMap = cp.getHashCommand(td_tableName,message,process); 
		if(TransactionDetailMap.containsKey("ErrorInput"))
		{
			sbrProperty.append(TransactionDetailMap.get("ErrorInput"));
			return sbrProperty;
		}
			
		ViewHashtable.putAll(TransactionDetailMap);		
		
		t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("sms.tablename","Transaction_details","initializeToView",t.duration());
		return sbrProperty;	
	
	}	
	
	
	public String getId() {
		return tid;
	}	
	
	public Hashtable<Object,Object> getViewHashtable() {
		return ViewHashtable;
	}	
	
	public Vector<Object> getPropertyVector() {		
		return TransDetailVector;
	}	
	
	public Vector<Object> getOldPropertyVector() {		
		return OldTransDetailVector;
	}	
	
	public Vector<Object> getNewPropertyVector() {		
		return NewTransDetailVector;
	}

	
	public Hashtable<Object, Object> initializeToDelete() {
		// TODO Auto-generated method stub
		return null;
	}
	
	 /**
	 * is called when process is to insert in database
	 */
/* public void setProcessToAdd()
 {	
	 ExecutionTimer t = new ExecutionTimer();
		t.start();
	   
		//add	
	Hashtable<Object,Object> hashtable = new Hashtable<Object, Object>();
		hashtable.putAll(initializeToAdd());	
		
		System.out.println();
		System.out.println(TransDetailVector);
		System.out.println();			

		if(!hashtable.containsKey("ErrorInput"))
		{
			tdBean = new Transaction_details_Bean();
			
			tdBean.setDBManager(sqlDB);
			tdBean.setReqParam(reqParam);
			tdBean.setProcess(process);				
			tdBean.setTid(tid);
			tdBean.setPropertyVector(TransDetailVector);	
			
			tdBean.insert();
		}	
		 t.end();
			@SuppressWarnings("unused")
			TimerRecordFile timerFile=new TimerRecordFile("SMS.tablename","Transaction_details","processAdd",t.duration());
	       
	}*/
	
 
 	/**
	 * is called when process is to update in database
	 */
	/*public void setProcessToUpdate()
	{
		 ExecutionTimer t = new ExecutionTimer();
			t.start();
		   
		//mod	
		sbrDTB = new StringBuffer();
		sbrDTB.append(initializeToUpdate());
		
		System.out.println("old "+OldTransDetailVector);
		System.out.println("new "+NewTransDetailVector);		
			
		tdBean = new Transaction_details_Bean();
		
		tdBean.setDBManager(sqlDB);
		tdBean.setReqParam(reqParam);	
		tdBean.setProcess(process);			
		if(!OldTransDetailVector.isEmpty())
			tdBean.setOldPropertyVector(OldTransDetailVector);	
		if(!NewTransDetailVector.isEmpty())
			tdBean.setNewPropertyVector(NewTransDetailVector);
		//tdBean.setTid(tid);
		tdBean.update();
	 t.end();
	@SuppressWarnings("unused")
	TimerRecordFile timerFile=new TimerRecordFile("SMS.tablename","Transaction_details","processMod",t.duration());
	       			
	}*/
	
	
	/*@SuppressWarnings("unchecked")
	public void processSms()
	{		
		//add	
		if(process.equalsIgnoreCase("add"))
			processAdd();
		else
			processMod();//mod		
	}
	
	public void setProcessToView()
	{						
		//view		
	
		ExecutionTimer t = new ExecutionTimer();
		 t.start();
				
		sbrDTB = new StringBuffer();
		sbrDTB.append(initializeToView());
		
		System.out.println(ViewHashtable);
		
		tdBean = new Transaction_details_Bean();
		
		tdBean.setDBManager(sqlDB);
		tdBean.setReqParam(reqParam);	
		tdBean.setProcess(process);			
		
		tdBean.setViewHashtable(ViewHashtable);
		
		sbrDTB.append(tdBean.view());
		
		System.out.println(sbrDTB);
		
		t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("pool.tablename","Td_property_details","getView",t.duration());
			
	}
	
	*/
	public StringBuffer generatesms(StringBuffer strbuffer)
	{
		StringBuffer stringbuffer= new StringBuffer();
		String splitbuffer[] = strbuffer.toString().split("\n");
		if(splitbuffer.length>0)
		{
			try 
			{
				String splitheading[] = splitbuffer[0].split("\t");
				ResultSet rs = sqlDB.getSelect("SELECT fieldname,from_master FROM command where msgtype like 'transaction_details'"+ " and process='view'" );
				Hashtable<Object , Object> transactionmap = new Hashtable<Object, Object>();
				while(rs.next())
				{	
					transactionmap.put(rs.getString("fieldname"), rs.getString("from_master"));
				}
				StringBuffer heading = new StringBuffer();
				StringBuffer Field = new StringBuffer();
				for(int j=0;j<splitheading.length;j++)
				{
					if(!transactionmap.containsKey(splitheading[j]))
						heading.append(splitheading[j]+"\t");
				}
				
				MessageGenerator msg=new MessageGenerator(sqlDB);
				for(int i=1;i<splitbuffer.length;i++)
				{
					Hashtable<Object , Object> table =new Hashtable<Object, Object>();
				  	String splitfield[] =splitbuffer[i].split("\t");
				  	for(int j=0;j<splitfield.length;j++)
				  	{	
				  		if(transactionmap.containsKey(splitheading[j]))
				  		table.put(splitheading[j],splitfield[j]);
				  		else
				  			Field.append(splitfield[j]+"\t");
				  	}
				  	stringbuffer.append(msg.convertToMessage("transaction_details","view",table));
				}
				SmsTd_property_details smstd_property_details = new SmsTd_property_details();
				stringbuffer.append(smstd_property_details.generatesms(heading.append("\n"+Field)));
			}
			catch (Exception e) 
			{
				e.printStackTrace();
			}
			
		}
		return stringbuffer;
		
	}
}
